package com.blockmeta.bbs.immodule.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import com.blankj.utilcode.util.LogUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseFragment;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.bean.HongbaoCreateRequest;
import com.blockmeta.bbs.immodule.bean.HongbaoDetail;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.databean.HongBaoContentBean;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.net.api.CreateHongbaoApi;
import com.blockmeta.bbs.immodule.net.api.GetMyCoinByUidApi;
import com.blockmeta.bbs.immodule.widget.HongBaoCreateDialogFragment;
import com.blockmeta.bbs.immodule.widget.LengthLimitEditText;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import butterknife.BindView;
import butterknife.OnClick;

import static com.blockmeta.bbs.immodule.Constants.CHATTYPE;
import static com.blockmeta.bbs.immodule.Constants.TOUSERID;

public class HongBaoCreateFragment extends BaseFragment {

    @BindView(R2.id.et_total_num)
    EditText mEtTotalNum;
    @BindView(R2.id.tv_remain_count)
    TextView mTvRemainCount;
    @BindView(R2.id.et_hongbao_count)
    EditText mEtHongbaoCount;
    @BindView(R2.id.tv_member_count)
    TextView mTvMemberCount;
    @BindView(R2.id.edt_remark)
    LengthLimitEditText mEtRemark;
    @BindView(R2.id.tv_hongbao_type)
    TextView mTvHongbaoType;
    @BindView(R2.id.btn_send_hongbao)
    Button mBtnSendHongbao;
    @BindView(R2.id.layout_hongbao_count)
    ConstraintLayout mLayoutHongbaoCount;
    @BindView(R2.id.tv_hongbao_count_tip)
    TextView mTvHongbaoCountTip;
    @BindView(R2.id.tv_totalnum_tip)
    TextView mTvTotalNumTip;
    @BindView(R2.id.tv_totalnum)
    TextView mTvTotalNum;
    @BindView(R2.id.tv_unit)
    TextView mTvUnit;

    private int mAmount;
    private int mGroupCount;


    public static final String HONGBAO_TYPE = "type";

    private int mType;
    public int mChatType;
    public long mToUserId;

    public static Fragment newInstance(int type, int mChatType, long mToUserId) {
        HongBaoCreateFragment f = new HongBaoCreateFragment();
        f.setArguments(buildArgs(type, mChatType, mToUserId));
        return f;
    }

    public static Bundle buildArgs(final int type, int mChatType, long mToUserId) {
        Bundle bundle = new Bundle();
        bundle.putInt(HONGBAO_TYPE, type);
        bundle.putInt(CHATTYPE, mChatType);
        bundle.putLong(TOUSERID, mToUserId);
        return bundle;
    }


    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.layout_hongbao_create, container, false);
    }

    @Override
    public void initView() {
        mType = getArguments().getInt(HONGBAO_TYPE);
        mChatType = getArguments().getInt(CHATTYPE);
        mToUserId = getArguments().getLong(TOUSERID);

        if(Params.HONGBAO_EQUAL == mType){
            mTvHongbaoType.setText("均");
            mTvTotalNum.setText("单个金额");
        }else if(Params.HONGBAO_LUCKY == mType){
            mTvHongbaoType.setText("拼");
        }else {
            mTvHongbaoType.setText("个");
        }
        mTvUnit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtTotalNum.requestFocus();
                InputMethodManager systemService = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                systemService.showSoftInput(mEtTotalNum, 0);
            }
        });
        if(mChatType == ChatMessage.MSG_TYPE_UCG){
            IMApplicationContext.getCircleDomainService().getGroup(mToUserId, new BaseResponseCallBack<String, IMUserEntity>() {
                @Override
                public void fail(String msg) {

                }

                @Override
                public void success(IMUserEntity imUserEntity) {
                    mGroupCount = imUserEntity.getGroupCount();
                    mTvMemberCount.setText(String.format("本群共%d人",imUserEntity.getGroupCount()));
                }
            });
        }else {
            mTvMemberCount.setVisibility(View.GONE);
            mLayoutHongbaoCount.setVisibility(View.GONE);

        }
        mBtnSendHongbao.setEnabled(false);

        mEtTotalNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                caculateAmountAndBindBtn();
                checkInputLegal();
            }
        });
        mEtHongbaoCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                caculateAmountAndBindBtn();
                checkInputLegal();
            }
        });
        mEtRemark.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){

                    HongBaoCreateDialogFragment parentFragment = (HongBaoCreateDialogFragment) getParentFragment();
                    parentFragment.scrollUp();
                }else {
                    HongBaoCreateDialogFragment parentFragment = (HongBaoCreateDialogFragment) getParentFragment();
                    parentFragment.scrollDown();

                }
            }
        });

        getMyCoinFromNet();
    }

    private void checkInputLegal() {
        String numTip = "";
        String countTip = "";
        boolean btnEnable = true;
        String totalNumStr = mEtTotalNum.getText().toString().trim();
        int totalNum = TextUtils.isEmpty(totalNumStr) ? 0 : Integer.parseInt(totalNumStr);
        String hongbaoCountStr = mEtHongbaoCount.getText().toString().trim();
        int hongbaoCount = TextUtils.isEmpty(hongbaoCountStr) ? 0 : Integer.parseInt(hongbaoCountStr);
        if(mChatType == ChatMessage.MSG_TYPE_UCG) {
            if(totalNum == 0){
                numTip = "金额不能为0";
                btnEnable = false;
            }else if(mAmount == 0){
                numTip = "剩余金币数为0";
                btnEnable = false;
            }else if(mAmount != 0 && totalNum > mAmount){
                numTip = "金币超过剩余数量";
                btnEnable = false;
            }else if(mAmount != 0 && Params.HONGBAO_EQUAL == mType && totalNum * hongbaoCount > mAmount){
                numTip = "金币超过剩余数量";
                btnEnable = false;
            }


            if(hongbaoCount == 0){
                countTip = "个数不能为0";
                btnEnable = false;
            }else if(mGroupCount == 0){
                countTip = "群人数为0";
                btnEnable = false;
            }else if(mGroupCount != 0 && hongbaoCount > mGroupCount){
                countTip = "红包数量超过人数";
                btnEnable = false;
            }else if(mAmount != 0 && hongbaoCount > mAmount){
                countTip = "红包数量大于剩余金额";
                btnEnable = false;
            }else if(Params.HONGBAO_LUCKY == mType && totalNum != 0 && hongbaoCount > totalNum){
                countTip = "红包数量大于发送金额";
                btnEnable = false;
            }
            mTvTotalNumTip.setText(numTip);
            mTvHongbaoCountTip.setText(countTip);
            mBtnSendHongbao.setEnabled(btnEnable);
        }else {
            if(totalNum == 0){
                numTip = "金额不能为0";
                btnEnable = false;
            }else if(mAmount == 0){
                numTip = "剩余金币数为0";
                btnEnable = false;
            }else if(mAmount != 0 && totalNum > mAmount){
                numTip = "金币超过剩余数量";
                btnEnable = false;
            }


            mTvTotalNumTip.setText(numTip);
            mBtnSendHongbao.setEnabled(btnEnable);
        }

    }

    private void caculateAmountAndBindBtn() {
        int amount = 0;
        if(mChatType == ChatMessage.MSG_TYPE_UCG) {
            if (!TextUtils.isEmpty(mEtTotalNum.getText()) && !TextUtils.isEmpty(mEtHongbaoCount.getText())) {
                if(Params.HONGBAO_EQUAL == mType){
                    amount = Integer.parseInt(mEtTotalNum.getText().toString()) * Integer.parseInt(mEtHongbaoCount.getText().toString());
                }else if(Params.HONGBAO_LUCKY == mType){
                    amount = Integer.parseInt(mEtTotalNum.getText().toString());
                }
            }
        }else {
            if (!TextUtils.isEmpty(mEtTotalNum.getText())) {
                amount = Integer.parseInt(mEtTotalNum.getText().toString()) * 1;
            }
        }
        mBtnSendHongbao.setText(String.format("共%d金币，发红包", amount));
    }

    private void getMyCoinFromNet() {
        RetrofitFactory.getRootRetrofit().create(GetMyCoinByUidApi.class)
                .getMyCoinByUidApi(AccountHelper.getUidInt())
                .compose(RxUtil.<Integer>rxSchedulerHelper())
                .compose(((RxAppCompatActivity) mContext).<Integer>bindToLifecycle())
                .subscribe(new CommonSubscriber<Integer>(mContext) {
                    @Override
                    public void onNext(Integer amount) {
                        LogUtils.i("author" + "getmycoin" + amount.toString());
                        mAmount = amount;
                        mTvRemainCount.setText(amount + "");
                    }
                });

    }


    @OnClick({R2.id.btn_send_hongbao})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.btn_send_hongbao) {

            String remark = mEtRemark.getText().toString().trim();
            if(TextUtils.isEmpty(remark)){
                remark = "恭喜发财大吉大利";
            }

            String totalNum = mEtTotalNum.getText().toString().trim();
            ProgressBarUtil.showProgress(mContext);
            HongbaoCreateRequest createRequest = new HongbaoCreateRequest();
            //
            createRequest.setBoxType(mType);
            if(mChatType == ChatMessage.MSG_TYPE_UCG){
                Integer totalNumInt = Integer.valueOf(totalNum);
                Integer userNumInt = Integer.valueOf(mEtHongbaoCount.getText().toString());
                createRequest.setCandyNum(Params.HONGBAO_EQUAL == mType ? totalNumInt * userNumInt : totalNumInt);
                createRequest.setUserNum(userNumInt);
            }else {
                Integer totalNumInt = Integer.valueOf(totalNum);
                createRequest.setCandyNum(totalNumInt);
                createRequest.setUserNum(1);
            }
            createRequest.setCandyType(1);
            createRequest.setRemark(remark);
            createRequest.setToId(mToUserId);
            createRequest.setToType(mChatType);
            LogUtils.i("author" + "sendhongbao" + createRequest.toString());


            final String finalRemark = remark;
            RetrofitFactory.getRetrofit().create(CreateHongbaoApi.class)
                    .createBox(createRequest)
                    .compose(RxUtil.<BaseCodeResponse<HongbaoDetail>>rxSchedulerHelper())
                    .compose(RxUtil.<HongbaoDetail>commonResultByCode())
                    .compose(((RxAppCompatActivity) mContext).<HongbaoDetail>bindToLifecycle())
                    .subscribe(new CommonSubscriber<HongbaoDetail>(mContext) {
                        @Override
                        public void onNext(HongbaoDetail detail) {
                            LogUtils.i("author" + "sendhongbao result" + detail.toString());
                            HongBaoContentBean hongBaoContentBean = new HongBaoContentBean();
                            hongBaoContentBean.setTitle(finalRemark);
                            hongBaoContentBean.setType(mType);
                            hongBaoContentBean.setId(detail.getId());

                            HongBaoCreateDialogFragment parentFragment = (HongBaoCreateDialogFragment) getParentFragment();
                            HongBaoCreateDialogFragment.OnOutPutListener onOutPutListener = parentFragment.getOnOutPutListener();
                            if(onOutPutListener != null){
                                onOutPutListener.onOutPutText(ChatMessage.CONTENT_TYPE_HONGBAO, detail.getMessageId(), hongBaoContentBean.toJsonString());
                            }
                            parentFragment.dismiss();
                        }
                    });

        }
    }
}
